package com.jy.appmarket.utils;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class GetInstalledPackagesCompat {
	public static List<PackageInfo> getInstalledPackages(Context context, int flags) {
		final PackageManager pm = context.getPackageManager();
		try {
			return pm.getInstalledPackages(flags);
		} catch (Exception ignored) {
			// we don't care why it didn't succeed. We'll do it using an
			// alternative way instead
		}
		// use fallback:
		Process process;
		List<PackageInfo> result = new ArrayList<PackageInfo>();
		BufferedReader bufferedReader = null;
		try {
			process = Runtime.getRuntime().exec("pm list packages");
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				final String packageName = line.substring(line.indexOf(':') + 1);
				final PackageInfo packageInfo = pm.getPackageInfo(packageName, flags);
				result.add(packageInfo);
			}
			process.waitFor();
		} catch (Exception e) {
			LogUtil.e("GetInstalledPackagesCompat", "failed to get installed packages", e);
			// e.printStackTrace();
		} finally {
			safeClose(bufferedReader);
		}
		return result;
	}

	private static void safeClose(Closeable c) {
		if (c == null) {
			return;
		}
		try {
			c.close();
		} catch (IOException e) {
			// do nothing
		}
	}
}
